﻿using Microsoft.EntityFrameworkCore;
using MyBlog2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyBlog2.Repository
{
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext _context;

        public UserRepository(AppDbContext context)
        {
            this._context = context;
        }

        public User GetUserByUsername(string username)
        {
            var user = _context.Users.FirstOrDefault(u=>u.UserName == username);
            //User u = new User
            //{
            //    Id = user.Id,
            //    UserName = user.UserName,
            //    Password = string.Empty,
            //    Nickname = user.Nickname,
            //    Email = user.Email,
            //    Avatar = user.Avatar,
            //    Articles = user.Articles
            //};
            //return u;
            return user;
        }

        public string GetUseridByUsername(string username)
        {
            return _context.Users.FirstOrDefault(u=>u.UserName == username).Id.ToString();
        }


        /// <summary>
        /// 管理员基本信息
        /// </summary>
        /// <returns></returns>
        public User GetUserInfo()
        {
            var user = _context.Users.First();
            User u = new User
            {
                UserName = user.UserName,
                Nickname = user.Nickname,
                Email = user.Email,
                Avatar = user.Avatar,
                AboutMe = user.AboutMe,
            };
            return u;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public User Login(User user)
        {
            string userPwd = Utils.GetMD5_32(user.Password);
            return _context.Users.FirstOrDefault(u => u.UserName == user.UserName && u.Password == userPwd);
        }
    }
}
